package org.csu.myPetStore.web.servlet.Login;

import org.csu.myPetStore.domain.Account;
import org.csu.myPetStore.service.AccountService;
import org.csu.myPetStore.service.LogcatService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;

public class RegisterAccountServlet extends HttpServlet {

    private static final String LOGIN = "/WEB-INF/jsp/account/SignonForm.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        LogcatService logcatService = new LogcatService();

        Account account = getAccount(req,resp);

        AccountService accountService = new AccountService();
        accountService.insertAccount(account);
        accountService.insertSignon(account);

        //添加日志信息
        java.util.Date date = new java.util.Date();
        Date datesql = new Date(date.getTime());
        logcatService.InsertLogCat(account.getUsername(),account.getUsername() + " Register Successfully  at " + datesql.toString());


        req.getRequestDispatcher(LOGIN).forward(req,resp);
    }

    protected Account getAccount(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        Account account = new Account();
        account.setUsername(req.getParameter("username"));
        account.setPassword(req.getParameter("password"));
        account.setFirstName(req.getParameter("account.firstName"));
        account.setLastName(req.getParameter("account.lastName"));
        account.setEmail(req.getParameter("account.email"));
        account.setPhone(req.getParameter("account.phone"));
        account.setAddress1(req.getParameter("account.address1"));
        account.setAddress2(req.getParameter("account.address2"));
        account.setCity(req.getParameter("account.city"));
        account.setState(req.getParameter("account.state"));
        account.setZip(req.getParameter("account.zip"));
        account.setCountry(req.getParameter("account.country"));
        account.setLanguagePreference(req.getParameter("account.languagePreference"));
        account.setFavouriteCategoryId(req.getParameter("account.favouriteCategoryId"));

        return account;
    }

}
